<template>
  <div class="upload-file">
    <el-upload
      :action="uploadFileUrl"
      :file-list="fileList"
      :on-error="handleUploadError"
      :show-file-list="false"
      :headers="headers"
      :limit="1"
      :on-exceed="handleExceed"
      :http-request="uploadRequest"
      class="upload-file-uploader"
      ref="upload"
      multiple
    >
      <!-- 上传按钮
      <el-button size="mini" type="primary">选取文件</el-button> -->
      <!-- 上传提示
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
        <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
        的文件
      </div> -->
    </el-upload>
    <!-- 文件列表 -->
        <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
          <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in list">
            <el-link :href="file.url" :underline="false" target="_blank">
              <span class="el-icon-document"> {{ file.name }}</span>
            </el-link>
            <!-- <div class="ele-upload-list__item-content-action">
              <el-link :underline="false" @click="handleDelete(file.name)" type="danger">删除</el-link>
            </div> -->
          </li>
        </transition-group>
  </div>
</template>

<script>
  import { getToken } from "@/utils/auth";
  import request from '@/utils/request'
  export default {
    props: {
      // 值
      value: [String, Object, Array],
      // 大小限制(MB)
      fileSize: {
        type: Number,
        default: 500,
      },
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: {
        type: Array,
        default: () => ["doc", "xls", "ppt", "txt", "pdf",'png', 'jpg', 'jpeg', 'zip', 'rar'],
      },
      // 是否显示提示
      isShowTip: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        fileList: [],
        temp:1,
      };
    },
    computed: {
      // 是否显示提示
      showTip() {
        return this.isShowTip && (this.fileType || this.fileSize);
      },
      list(){

        //组装filelist

        if(this.value){
          // console.log('this.value',this.value)
          this.value=this.value.replace('null,','')
          const li=this.value.split(",");
          // 然后将数组转为对象数组
          return li.map((item) => {
              if (typeof item === "string") {
                item = { name: this.getFileName(item), url: item };
              }
            item.uid = item.uid || new Date().getTime() + this.temp++;
            return item;
          });
        }else{
          this.fileList = [];
          return [];
        }
      },
    },
    methods: {
      // 删除文件
      handleDelete(filename) {
        let r = JSON.stringify(filename);
        let fi=this.value.split(',');
         this.value=null
        this.fileList=fi.map((item) => {
           let l = JSON.stringify(this.getFileName(item));
           if(r==l){
             // console.log(filename,'=====',item)
           }else{
             this.value=this.value+","+item;
           }
        })
          this.$emit("input", this.value);
          this.fileList = this.list;
           // console.log('删除文件后结束',this.fileList)

      },
      // 上传前校检格式和大小
      handleBeforeUpload(file) {
        // 校检文件类型
        if (this.fileType) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          const isTypeOk = this.fileType.some((type) => {
            if (file.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          });
          if (!isTypeOk) {
            this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
            return false;
          }
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        return true;
      },
      // 文件个数超出
      handleExceed() {
        this.$message.error(`只允许上传单个文件`);
      },
      // 上传失败
      handleUploadError(err) {
        this.$message.error("上传失败, 请重试");
      },
      uploadRequest(param) {
        let fileObj = param.file;
        let form = new FormData();
        form.append('file', fileObj);
        return request({
          url: '/common/upload',
          method: 'post',
          data: form
        }).then(res => {
            let isnew=false;
            if(this.value==''){
              isnew=true;
            }
            // const item = { name: this.getFileName(res.url), url: res.url };
            // item.uid = item.uid || new Date().getTime() + this.temp++;

            // this.fileList.push(item)
            if(this.value===null){
              this.value=res.url;
            }else{
              this.value=this.value+","+res.url;
            }
            
          if(isnew){//处理都好拼接前面的逗号
            this.value=this.value.substr(1,this.value.length)
          }
            this.$emit("input",  this.value);
console.log('选择文件的value',this.value)
           this.fileList = this.list;
           console.log('选择文件上传后',this.fileList)
            this.$message.success("上传成功");

          }).catch(res => {
            this.$message.error("上传失败");
          });
      },
      // // 删除文件
      // handleRemove(file, fileList) {
      //   let index = fileList.findIndex( fileItem => {
      //       return fileItem.uid === file.uid
      //     })
      //   this.fileList.splice(index, 1);
      //   this.value='';
      //   this.fileList.filter((item,i)=>{
      //     this.value=this.value+","+item.url;
      //   })
      //   this.$emit("input", this.value);
      // },

      // 获取文件名称
      getFileName(name) {
        if (name.lastIndexOf("/") > -1) {
          return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
        } else {
          return "";
        }
      },
    },
    created() {
      this.fileList = this.list;
      console.log('页面创建时',this.fileList)
    },
  };
</script>

<style scoped lang="scss">
  .upload-file-uploader {
    margin-bottom: 5px;
  }
  .upload-file-list .el-upload-list__item {
    border: 1px solid #e4e7ed;
    line-height: 2;
    margin-bottom: 10px;
    position: relative;
  }
  .upload-file-list .ele-upload-list__item-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: inherit;
  }
  .ele-upload-list__item-content-action .el-link {
    margin-right: 10px;
  }
</style>
